#include<iostream>
#include<unistd.h>
#include<sys/types.h>
#include<wait.h>
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;


#define N 2
#define NUM 1024

void Write(int wfd) //child
{
    string s="hello i am child!";
    pid_t self=getpid();
    int number=0;
    char buffer[NUM];
    int cnt=5;
    while(true)
    {
        sleep(2);
        //构建发送字符串
        // buffer[0]=0;
        // snprintf(buffer,sizeof(buffer),"%s-%d-%d",s.c_str(),self,number++);
        // cout<<buffer<<endl;
        // write(wfd,buffer,strlen(buffer));
        char c='c';
        write(wfd,&c,1);
        number++;
        cout<<number<<endl;
        if(number>5) break;
    }
}
void   Read(int rfd) //father
{
    char buffer[NUM];
    while(true)
    {
        buffer[0]=0;
        ssize_t n=read(rfd,buffer,sizeof(buffer));
        if(n>0)
        {
            buffer[n]=0;
            cout<<"father get a message["<<getpid()<<"]#"<<buffer<<endl;
        }
        else if(n==0)
        {
            cout<<"father read file done"<<endl;
            break;
        }
        else break;
    }

}

int main()
{
    int pipefd[N]={0};
    int n=pipe(pipefd);
    if(n<0)
    {
        return -1;
    }
    cout<<"pipefd[0]:"<<pipefd[0]<<"pipefd[1]:"<<pipefd[1]<<endl;

    pid_t id=fork();
    if(id<0)
    {
        perror("fork fail");
        return 1;
    }
    else if(id==0) //child
    {
        close(pipefd[0]);
        //IPC code
        Write(pipefd[1]);
    }
    //father
    close(pipefd[1]);
    //IPc code
    Read(pipefd[0]);
    //进程等待
    pid_t ret=waitpid(id,nullptr,0);
    if(ret<0)   return 3;
    close(pipefd[0]);
    return 0;
}